package com.ruoyi.web.controller.cs;

import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.ruoyi.common.annotation.CheckSwitch;
import com.ruoyi.common.core.controller.BasicsController;
import com.ruoyi.common.core.domain.Response;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.core.page.ResponsePageInfo;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.cs.domain.vo.VIPInfoVo;
import com.ruoyi.cs.service.ITUserService;
import com.ruoyi.framework.web.service.TokenService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import io.swagger.models.auth.In;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.cs.domain.TVipGrade;
import com.ruoyi.cs.service.ITVipGradeService;

/**
 * VIP等级表
 * 
 * @author ruoyi
 * @date 2023-03-02
 */
@Api(tags = {"VIP等级管理"})
@RestController
@RequestMapping("/cs/vipgrade")
public class TVipGradeController extends BasicsController
{
    private Logger log = LoggerFactory.getLogger(TVipGradeController.class);
    @Autowired
    private ITVipGradeService tVipGradeService;
    @Autowired
    private ITUserService tUserService;
    @Autowired
    private TokenService tokenService;

    @ApiOperation("VIP等级列表")
    @PreAuthorize("@ss.hasPermi('system:grade:list')")
    @PostMapping("/list")
    public ResponsePageInfo<TVipGrade> list(@RequestBody TVipGrade tVipGrade)
    {
        startPage(tVipGrade.getPageNum(),tVipGrade.getPageSize());
        List<TVipGrade> list = tVipGradeService.selectTVipGradeList(tVipGrade);
        if(!CollectionUtils.isEmpty(list)){
            List<Map<String,Object>> vipMap = tUserService.groupCountVipNum();
            for (TVipGrade vipGrade : list) {
                if(vipMap.size()>0){
                    List<Map<String,Object>> filterMap =  vipMap.stream().filter(map -> vipGrade.getVip().intValue() == Integer.parseInt(map.get("userVip").toString())).collect(Collectors.toList());
                   if(filterMap.size()>0){
                       vipGrade.setVipUserNum(Long.parseLong(filterMap.get(0).get("vipNum").toString()));
                   }else {
                       vipGrade.setVipUserNum(0);
                   }
                }else {
                    vipGrade.setVipUserNum(0);
                }
            }
        }
        return toResponsePageInfo(list);
    }

    @ApiOperation("新增获取当前VIP")
    @GetMapping(value = "/getCurryVip")
    public Response getCurryVip()
    {
        return Response.success(tVipGradeService.getMaxVip()+1);
    }

    @ApiOperation("新增VIP等级")
    @PreAuthorize("@ss.hasPermi('system:grade:add')")
    @Log(title = "新增VIP等级", businessType = BusinessType.INSERT)
    @PostMapping("add")
    public Response add(@RequestBody TVipGrade tVipGrade)
    {
        return toResponse(tVipGradeService.insertTVipGrade(tVipGrade));
    }

    @ApiOperation("修改VIP等级")
    @PreAuthorize("@ss.hasPermi('system:grade:edit')")
    @Log(title = "修改VIP等级", businessType = BusinessType.UPDATE)
    @PostMapping("edit")
    public Response edit(@RequestBody TVipGrade tVipGrade)
    {
        return toResponse(tVipGradeService.updateTVipGrade(tVipGrade));
    }

    @ApiOperation("删除VIP等级")
    @PreAuthorize("@ss.hasPermi('system:grade:remove')")
    @Log(title = "删除VIP等级", businessType = BusinessType.DELETE)
    @GetMapping("remove")
    @ApiImplicitParam(name = "id",value = "id" ,dataType = "long",required = true)
    public Response remove(Long id)
    {
        return toResponse(tVipGradeService.deleteTVipGradeById(id));
    }


    /**---------------------------------前端--------------------------------------------*/
    @ApiOperation("个人vip详情信息-web")
    @GetMapping(value = "/common/myVipInfo")
    public Response<VIPInfoVo> myVipInfo()
    {
        String userId = null;
        LoginUser loginUser = tokenService.getLoginUserWeb(ServletUtils.getRequest());
        if(loginUser != null){
             userId = loginUser.getUser().getLoginUserId();
        }
        return tVipGradeService.myVipInfo(userId);
    }

    @CheckSwitch
    @ApiOperation("vip等级奖励领取-web")
    @GetMapping(value = "/receive")
    @Log(title = "vip等级奖励领取", businessType = BusinessType.OTHER)
    @ApiImplicitParam(name = "vip",value = "vip等级" ,dataType = "long",required = true)
    public Response receive(long vip)
    {
        String userId = tokenService.getLoginUserId();
        try {
            return tVipGradeService.receive(userId,vip);
        } catch (Exception e) {
            log.error("VIP等级奖励领取异常:{}",e.getMessage());
            return Response.fail("领取失败,系统异常");
        }
    }

    @ApiOperation("会员特权列表-web")
    @GetMapping(value = "/common/vipList")
    public Response<List<TVipGrade>> vipList()
    {
        return Response.success(tVipGradeService.vipList());
    }

    @ApiOperation("计算充值和奖励-web")
    @GetMapping(value = "/computeVip")
    public Response<Map> computeVip()
    {
        String userId = tokenService.getLoginUserId();
        return tVipGradeService.computeVip(userId);
    }


}
